from os import name

if name != 'posix':
    raise Exception("Only POSIX OS mutex is supported")
else:
    import posix_ipc
    from os import PathLike, fspath

    class Mutex:
        def __init__(self, name: str | PathLike, initial_value: int = 1, timeout: int = posix_ipc.USER_SIGNAL_MAX):
            self.name = fspath(name)
            if len(self.name) > 251:
                self.name = self.name[-251:]
            if not self.name.startswith('/'):
                self.name = f'/{self.name}'
            self.name = self.name.replace('/', '_')
            self.name = "/" + self.name[1:]
            self.timeout = timeout
            self.initial_value = initial_value
            self._sem = None
            self._init()

        def _init(self):
            if self._sem is None:
                self._sem = posix_ipc.Semaphore(self.name, posix_ipc.O_CREAT, initial_value=self.initial_value)

        def __enter__(self):
            self._init()
            self.acquire()
            return self

        def __exit__(self, exc_type, exc_val, exc_tb):
            self.release()
            self.close()

        def acquire(self, timeout: int =None):
            if timeout is None:
                timeout = self.timeout
            return self._sem.acquire(timeout)

        def release(self):
            return self._sem.release()

        def close(self):
            self._sem.close()
            self._sem = None
